package org.lanqiao.tjut.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.lanqiao.tjut.bean.TBAdminBean;
import org.lanqiao.tjut.bean.TBStudentBean;
import org.lanqiao.tjut.model.ModelFactory;
import org.lanqiao.tjut.myUtils.MyUtils;

/**
 * 学生信息添加 StudentInfoAdd
 */
@WebServlet("/StudentInfoAddServlet2")
@MultipartConfig(maxFileSize=5000000)//注意设置文件大小的单位是bit
public class StudentInfoAddServlet2 extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获取客户端表表单数据,将表单数据存储到实体对象中
				TBStudentBean stuB = MyUtils.getNewInstance(TBStudentBean.class);
				stuB.setStu_name(request.getParameter("stuName"));
				stuB.setStu_sex(request.getParameter("stuSex"));
				stuB.setStu_birthday(MyUtils.convertString2Date(request.getParameter("stuBirthday"), "yyyy-MM-dd"));
				stuB.setStu_address(request.getParameter("stuAddress"));
				stuB.setStu_tel(request.getParameter("stuTel"));
				stuB.setStu_department(MyUtils.convertString2Integer(request.getParameter("stuDepartment")));
				//=====文件上传开始=====//
				//处理文件对象
				//获取文件对象part，part名还是指定form表单的file控件的name属性
				Part part=request.getPart("stuImg");
				//获取上传的文件名
				String strFileOldName=part.getSubmittedFileName();
				//获取网站的根目录（相对于服务器的盘符）
				String realPath=request.getServletContext().getRealPath("/");
				//组织上传文件保存的路径
				String uploadFilePath="uploadfiles/stuImgs/";
				//验证目录是否在服务器上存在，如果不存在则创建该目录
				File f=new File(realPath+uploadFilePath);
				if(!f.exists()){
					f.mkdirs();
				}
				System.out.println("打印上传文件目录"+f.getAbsolutePath());
				//获取上传文件的后缀名
				String strFileType=strFileOldName.substring(strFileOldName.lastIndexOf('.'));
				//上传文件名的前缀
				String strFilePrefix="stuImg";
				//创建上传文件名格式：前缀_UUID随机编号.文件后缀
				String strUploadFileName=strFilePrefix+UUID.randomUUID()+strFileType;
				//进行文件上传
				part.write(realPath+uploadFilePath+strUploadFileName);
				//保存文件相对路径
				stuB.setStu_img(uploadFilePath+strUploadFileName);
				//=======文件上传结束======//
				// 输出打印前台表单数据
				System.out.println("stu::"+stuB.toString());
				// 调用model层进行数据库保存
				int i = ModelFactory.getStudentInfoModelInstance().saveOrUpdateStudentInfo(stuB);
				// 保存之后的跳转处理
				if (i > 0) {
					// 保存成功
					request.getRequestDispatcher("WEB-INF/logined/studentInfoManager/studentInfoAddDetails.jsp").forward(request,
							response);
				} else {
					// 保存失败

				}
	}
}